package com.njwb.day16.dom.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public final class DbUtil {

    private static ThreadLocal<Connection> threadLocal  = new ThreadLocal<>() ;
    private static DataSource dataSource ;
    private static Properties properties = new Properties() ;

    private DbUtil(){};
    //加载util类的实现的初始化操作
    static{
        InputStream is = DbUtil.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 获取连接
    public static  Connection getConnection() throws SQLException {
        Connection connection = threadLocal.get();
        if(connection==null) {
            connection = dataSource.getConnection();
            threadLocal.set(connection);
        }
        return connection ;
    }


    //关闭连接
    public static void closeConnection() throws  SQLException{
        Connection connection = threadLocal.get();
        if(connection!=null) {
            connection.close();
            threadLocal.remove();
        }
    }


    public static void closeResource(ResultSet rs, PreparedStatement pstmt) {
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(pstmt!=null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
